package com.person.webdemoproject2.intercepter;

import com.alibaba.fastjson2.JSON;
import com.person.webdemoproject2.pojo.Result;
import com.person.webdemoproject2.utils.jwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
@Slf4j
public class LoginCheckinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");

        String url = request.getRequestURI().toString();
        log.info(url);

        if (url.contains("login")||url.contains("set")) {
            log.info("登录操作");

            return true;
        }
        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)){
            log.info("未登录");
            Result.error("NOT_LOGIN");
            String notLogin = JSON.toJSONString(Result.error("NOT_LOGIN"));
            response.getWriter().write(notLogin);
            return false;

        }

        try {
            jwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            Result.error("NOT_LOGIN");
            String notLogin = JSON.toJSONString(Result.error("NOT_LOGIN"));
            response.getWriter().write(notLogin);
            return false;
        }
        log.info("令牌合法");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");

    }
}
